package com.breeze.components.web.exception;

import cn.hutool.core.bean.BeanUtil;
import com.breeze.components.core.exception.ApiException;
import com.breeze.components.core.exception.error.ErrorCode;
import com.breeze.components.web.core.ResponseDTO;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

/**
 * @author breeze
 */
@Slf4j
@Controller
public class ErrorController extends BasicErrorController {

  public ErrorController(ServerProperties serverProperties) {
    super(new DefaultErrorAttributes(), serverProperties.getError());
  }

  @Override
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    // 获取原始的错误信息
    HttpStatus status = getStatus(request);
    Map<String, Object> body =
        getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
    ResponseDTO<Object> fail =
        ResponseDTO.fail(new ApiException(ErrorCode.Client.REQUEST_NOT_FOUND));
    Map<String, Object> bean = BeanUtil.beanToMap(fail, true, true);
    body.putAll(bean);
    body.put("code", status.value());
    body.put("msg", status.getReasonPhrase());
    return new ResponseEntity<>(body, status);
  }
}
